<template>
	<view class="bg-white margin-md padding-md border-radius-md">
		<uv-form labelPosition="left" :model="form" :rules="rules" ref="formRef" labelWidth="80" errorType="toast">
			<uv-form-item label="事件名称" prop="title" borderBottom>
				<uv-input v-model="form.title" placeholder="请输入事件名称" border="none"></uv-input>
			</uv-form-item>
			<uv-form-item label="事件单位" prop="unit" borderBottom>
				<uv-input v-model="form.unit" placeholder="请输入事件单位" border="none"></uv-input>
			</uv-form-item>
			<uv-form-item label="初始数量" prop="init_num" borderBottom>
				<uv-input type="number" :min="0" v-model="form.init_num" placeholder="请输入初始数量" border="none"></uv-input>
			</uv-form-item>
		</uv-form>
	</view>
	<fixed-button :is-loading="submiting" @on-tap="onSubmit"></fixed-button>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { createThingOption, getThingOption, updateThingOption } from '@/api';
import { onLoad } from '@dcloudio/uni-app';

interface ThingOptionForm {
	[key: string]: any;
	id: number;
	title: string;
	unit: string;
	init_num: number | string;
}

var form = ref<ThingOptionForm>({
	id: 0,
	title: '',
	unit: '',
	init_num: ''
});

var rules = {
	title: {
		type: 'string',
		required: true,
		message: '请填写事件名称',
		trigger: ['blur', 'change']
	},
	unit: {
		type: 'string',
		required: true,
		message: '请填写事件单位',
		trigger: ['blur', 'change']
	},
};

onLoad((op: any) => {
	if (op.id && op.id > 0) {
		getThingOption(op.id).then((res: any) => {
			for (const key in form.value) {
				form.value[key] = res.data[key];
			}
		});
	}
})

var submiting = ref(false);
var formRef = ref(null);

function onSubmit() {
	console.log(form.value);
	formRef.value?.validate().then(async () => {
		try {
			submiting.value = true;
			const from = JSON.parse(JSON.stringify(form.value));
			if (form.value.init_num === '') from.init_num = 1;

			if (form.value.id) {
				await updateThingOption(form.value.id, from);
			} else {
				await createThingOption(from);
			}

			_submitFinish()
			submiting.value = false;
		} catch (error) {
			submiting.value = false;
			console.log(error);
		}
	}).catch((err: any) => {
		console.log(err);
	});
}

function _submitFinish() {
	uni.showModal({
		title: '提示',
		content: '添加成功',
		showCancel: false,
		success: () => {
			uni.navigateBack();
		}
	})
}

</script>
